<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.4.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.4.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="本文属于对Java线程池的综合思考，如果您对Java线程池还不太了解，可以先收藏。 本文讲解如下几个内容：  当核心线程满时，先创建临时线程还是先加入队列？ 临时线程工作时间和方式？ 核心线程和临时线程获取活的方式？ 只有临时线程才能被销毁吗？ 何时触发拒绝策略？ 线程池如何调优？   题外话：做技术这一行，一定要沉的住气，把细节想透。">
<meta name="keywords" content="线程池">
<meta property="og:type" content="article">
<meta property="og:title" content="Java线程池的综合知识点">
<meta property="og:url" content="http://yoursite.com/2018/06/28/thread-pool-mix/index.html">
<meta property="og:site_name" content="ThinkMore">
<meta property="og:description" content="本文属于对Java线程池的综合思考，如果您对Java线程池还不太了解，可以先收藏。 本文讲解如下几个内容：  当核心线程满时，先创建临时线程还是先加入队列？ 临时线程工作时间和方式？ 核心线程和临时线程获取活的方式？ 只有临时线程才能被销毁吗？ 何时触发拒绝策略？ 线程池如何调优？   题外话：做技术这一行，一定要沉的住气，把细节想透。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://p5h71khzd.bkt.clouddn.com/ThreadPoolExecutor%E5%9B%BE%E8%A7%A3.png">
<meta property="og:updated_time" content="2018-08-13T12:42:13.366Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java线程池的综合知识点">
<meta name="twitter:description" content="本文属于对Java线程池的综合思考，如果您对Java线程池还不太了解，可以先收藏。 本文讲解如下几个内容：  当核心线程满时，先创建临时线程还是先加入队列？ 临时线程工作时间和方式？ 核心线程和临时线程获取活的方式？ 只有临时线程才能被销毁吗？ 何时触发拒绝策略？ 线程池如何调优？   题外话：做技术这一行，一定要沉的住气，把细节想透。">
<meta name="twitter:image" content="http://p5h71khzd.bkt.clouddn.com/ThreadPoolExecutor%E5%9B%BE%E8%A7%A3.png">






  <link rel="canonical" href="http://yoursite.com/2018/06/28/thread-pool-mix/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Java线程池的综合知识点 | ThinkMore</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?13172698bcdb7ab00b7d3ec112aae9c1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">ThinkMore</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">驽马十驾,功在不舍！</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="Toggle navigation bar">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />Home</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />Archives</a>
  </li>

      
      
    </ul>
  

  
    

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/06/28/thread-pool-mix/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="文敦复">
      <meta itemprop="description" content="思考的懒惰是真的懒惰！">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="ThinkMore">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java线程池的综合知识点
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              

              
                
              

              <time title="Created: 2018-06-28 20:39:30" itemprop="dateCreated datePublished" datetime="2018-06-28T20:39:30+08:00">2018-06-28</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Edited on</span>
                
                <time title="Modified: 2018-08-13 20:42:13" itemprop="dateModified" datetime="2018-08-13T20:42:13+08:00">2018-08-13</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/JUC/" itemprop="url" rel="index"><span itemprop="name">JUC</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文属于对Java线程池的综合思考，如果您对Java线程池还不太了解，可以先收藏。</p>
<p>本文讲解如下几个内容：</p>
<ul>
<li>当核心线程满时，先创建临时线程还是先加入队列？</li>
<li>临时线程工作时间和方式？</li>
<li>核心线程和临时线程获取活的方式？</li>
<li>只有临时线程才能被销毁吗？</li>
<li>何时触发拒绝策略？</li>
<li>线程池如何调优？</li>
</ul>
<blockquote>
<p>题外话：做技术这一行，一定要沉的住气，把细节想透。</p>
</blockquote>
<a id="more"></a>
<h1 id="先创建临时线程还是先加入队列"><a href="#先创建临时线程还是先加入队列" class="headerlink" title="先创建临时线程还是先加入队列"></a>先创建临时线程还是先加入队列</h1><p>这里要分为2种情况来看：JDK的和Tomcat（Dubbo也可以设置）的。</p>
<ul>
<li>JDK中线程池是优先加入队列，当队列满了，且当前线程数量没有达到最大线程的时候，会优先创建临时线程。</li>
<li>Tomcat的线程池是优先创建临时线程，当临时线程达到最大值才会加入队列。</li>
<li>Dubbo的线程池也是可以设置为先创建临时线程，详情见官方文档。</li>
</ul>
<p>为什么要如此设计了？我对此的理解如下所示：</p>
<p><code>Tomcat</code>大多处理的是<code>IO密集型</code>任务，线程大多数时候都是在阻塞在IO操作上，无事可做。与其如此，不如索性多创建线程，让<code>CPU</code>把时间片分给其他线程做后续操作。基于此考虑，优先创建线程。</p>
<p>实际项目中，因为临时线程不好控制，大多数建议核心线程和临时线程设置成一样大小，这种情况下，二者的表现其实是一致的了。</p>
<h1 id="临时线程工作时间和方式"><a href="#临时线程工作时间和方式" class="headerlink" title="临时线程工作时间和方式"></a>临时线程工作时间和方式</h1><p>JDK下的临时线程创建是在：新任务加入时，队列已被填满，同时核心线程数没有达到最大线程数的时候。</p>
<p>那么创建后临时线程如何进行工作：</p>
<ol>
<li>临时线程会通过<code>pool(time,unit)</code>的方式从队列中拉活干，干完1个任务继续干下一个任务,不会马上被销毁。。</li>
<li>当通过<code>pool(time,unit)</code>超过一定时间没有拉到活干，那么该临时线程被销毁（饿死了）</li>
</ol>
<p>这个地方有个理解误区：临时线程的创建仅仅是为了应付队列满后新加入的那个任务，其实不是的，临时线程创建后，不仅仅处理一个任务，会不提的从队列中poll活出来干。</p>
<h1 id="核心线程和临时线程获取任务的方式"><a href="#核心线程和临时线程获取任务的方式" class="headerlink" title="核心线程和临时线程获取任务的方式"></a>核心线程和临时线程获取任务的方式</h1><p>当某一个核心线程干完活后，会通过<code>take</code>阻塞的形式从任务队列中拉取任务，如果没有就会一直阻塞在那里，标准的生产者和消费者问题。</p>
<p>临时线程则是通过<code>poll(time,unit)</code>的方式拉活来干的。</p>
<h1 id="只有临时线程才能被销毁吗"><a href="#只有临时线程才能被销毁吗" class="headerlink" title="只有临时线程才能被销毁吗"></a>只有临时线程才能被销毁吗</h1><p>临时线程如果在指定的时间内没有通过<code>poll(time,unit)</code>拉到活干，那么就会被清理掉。</p>
<p>核心线程了？</p>
<p>核心线程默认是不允许被销毁的，不过如果通过<code>poolExecutor.allowCoreThreadTimeOut(true);</code>进行设置，当核心线程超过在构造函数定义的超时时间后，仍然会被销毁，官方doc说明如下。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Core pool size is the minimum number of workers to keep alive</span></span><br><span class="line"><span class="comment"> * (and not allow to time out etc) unless allowCoreThreadTimeOut</span></span><br><span class="line"><span class="comment"> * is set, in which case the minimum is zero.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">int</span> corePoolSize;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>我感觉我应该抽时间，把官方的doc好好读读。</p>
</blockquote>
<h1 id="何时触发拒绝策略"><a href="#何时触发拒绝策略" class="headerlink" title="何时触发拒绝策略"></a>何时触发拒绝策略</h1><p>通常情况下，我们认为只有1种，就是在：队列满了+核心线程与临时线程之后等于最大值时，又有任务加入就会触发。</p>
<p>但是还有一种情况，就是调用<code>shutdown</code>后，线程池会将正在执行的任务执行完毕后才真正退出，此时如果再加入了一个任务，也会触发拒绝策略。</p>
<h1 id="线程池如何调优"><a href="#线程池如何调优" class="headerlink" title="线程池如何调优"></a>线程池如何调优</h1><blockquote>
<p>以下内容肯定很多瑕疵！</p>
</blockquote>
<p>这个命题太大了，完全够写一篇文章了，个人技术和见识还有限，此处只能记录一些我知道的关于核心线程数的知识。</p>
<ul>
<li>如果任务是CPU密集型，核心线程作为<code>N+1</code>。N为CPU核心。</li>
<li>如果任务是IO密集型，核心线程设置为<code>2N+1</code></li>
<li>还有一个经典的公式：（ 任务等待时间/任务处理时间 + 1 ）<em> N </em> CPU利用率</li>
</ul>
<p>第三个公式，其中每个参数如何获取了？任务处理时间可以通过运行多次任务取平均的方式获取，CPU利用率？任务等待时间了？还请知道的小伙伴不吝赐教。</p>
<blockquote>
<p> 个人感觉应该看业务形态，业务看重吞吐量还是时延，通过测试来得到。</p>
<p>核心线程增多，吞吐量是先上升后下降？</p>
<p>核心线程增多，时延保持稳定然后再下降？</p>
<p>上述理论个人猜想，等这段时间忙完了，好好测试下！</p>
</blockquote>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>有些时候面试官会问题，线程池有那几个参数，不需要死记硬背，通过理解来记忆。</p>
<p><img src="http://p5h71khzd.bkt.clouddn.com/ThreadPoolExecutor%E5%9B%BE%E8%A7%A3.png" alt="线程池执行图"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize,</span></span></span><br><span class="line"><span class="function"><span class="params">                          <span class="keyword">int</span> maximumPoolSize,</span></span></span><br><span class="line"><span class="function"><span class="params">                          <span class="keyword">long</span> keepAliveTime,</span></span></span><br><span class="line"><span class="function"><span class="params">                          TimeUnit unit,</span></span></span><br><span class="line"><span class="function"><span class="params">                          BlockingQueue&lt;Runnable&gt; workQueue,</span></span></span><br><span class="line"><span class="function"><span class="params">                          ThreadFactory threadFactory,</span></span></span><br><span class="line"><span class="function"><span class="params">                          RejectedExecutionHandler handler)</span></span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>您有任何建议和意见，请Email联系: <a href="mailto:hicode_club@163.com" target="_blank" rel="noopener">hicode_club@163.com</a></p>
<p>转载请保留出处 <a href="http://www.hicode.club" target="_blank" rel="noopener">HiCode 俱乐部</a> : <a href="http://www.hicode.club" target="_blank" rel="noopener">http://www.hicode.club</a></p>
</blockquote>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/06/25/hashcode-from-code/" rel="next" title="通过hashcode的源码来理解重写equals和hashcode">
                <i class="fa fa-chevron-left"></i> 通过hashcode的源码来理解重写equals和hashcode
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/06/29/seckill-1/" rel="prev" title="秒杀业务的解决方案总结和思考">
                秒杀业务的解决方案总结和思考 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">文敦复</p>
              <p class="site-description motion-element" itemprop="description">思考的懒惰是真的懒惰！</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">39</span>
                    <span class="site-state-item-name">posts</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">37</span>
                    <span class="site-state-item-name">categories</span>
                  
                </div>
              

              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#先创建临时线程还是先加入队列"><span class="nav-number">1.</span> <span class="nav-text">先创建临时线程还是先加入队列</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#临时线程工作时间和方式"><span class="nav-number">2.</span> <span class="nav-text">临时线程工作时间和方式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#核心线程和临时线程获取任务的方式"><span class="nav-number">3.</span> <span class="nav-text">核心线程和临时线程获取任务的方式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#只有临时线程才能被销毁吗"><span class="nav-number">4.</span> <span class="nav-text">只有临时线程才能被销毁吗</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#何时触发拒绝策略"><span class="nav-number">5.</span> <span class="nav-text">何时触发拒绝策略</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#线程池如何调优"><span class="nav-number">6.</span> <span class="nav-text">线程池如何调优</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">7.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">文敦复</span>

  

  
</div>




  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme – <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Muse</a> v6.4.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.0"></script>



  



  










  





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
